package com.michaellou.Test;

import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.util.zip.GZIPInputStream;  
import java.util.zip.GZIPOutputStream;  
  
public class GzipTool {  
  
	private static String SUFFIX=".zip";
	
    public static void main(String[] args) {  
    	String file ="d:/test.txt";
        String gzipFile=readFileAndWriteGZip(file);  
        unZipFile(gzipFile);  
          
    }  
  
    public static String readFileAndWriteGZip(String file) {  
    	String gzipFile=file+SUFFIX;
        try {  
            //打开需压缩文件作为文件输入流   
            FileInputStream fin = new FileInputStream(file);   
            //建立压缩文件输出流   
            FileOutputStream fout = new FileOutputStream(gzipFile);   
            //建立gzip压缩输出流    
            GZIPOutputStream gzout = new GZIPOutputStream(fout);   
            //设定读入缓冲区尺寸   
            byte[] buf = new byte[1024];  
            int num;   
            while ((num = fin.read(buf)) != -1)   
            {   
                gzout.write(buf,0,num);   
            }   
  
            gzout.close();  
            fout.close();   
            fin.close();   
            } catch (Exception ex) {  
                System.err.println(ex.toString());  
            }
            return gzipFile;
    }  
  
    public static String unZipFile(String gzipFile) {  
    	String file=gzipFile.substring(0,gzipFile.indexOf(SUFFIX));
//    	String file="D:\\testtest.txt";
        try {
            //建立grip压缩文件输入流   
            FileInputStream fin = new FileInputStream(gzipFile);
            //建立gzip解压工作流   
            GZIPInputStream gzin = new GZIPInputStream(fin);   
            //建立解压文件输出流   
            FileOutputStream fout = new FileOutputStream(file);   
            byte[] buf=new byte[1024];   
            int num;   
            while ((num = gzin.read(buf,0,buf.length)) != -1)  
            {   
                fout.write(buf,0,num);   
            }   
              
            gzin.close();   
            fout.close();   
            fin.close();   
        } catch (Exception ex){  
            System.err.println(ex.toString());  
        }  
        return file;
    }  
  
  
  
}